package com.example.content.fragment.common

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.example.content.*
import com.example.content.adapter.recycle.BindListener
import com.example.content.adapter.recycle.RecyclerAdapter
import com.example.content.adapter.recycle.entity.HomeItemEntity
import com.example.content.adapter.recycle.entity.ItemEntity
import com.example.content.adapter.recycle.home.HomeRecyclerAdapter
import com.example.content.adapter.recycle.home.entity.IVItemEntity
import com.example.content.ext.convertUrl
import com.example.content.manager.ActivityMgr
import com.example.content.manager.GlobalMgr
import com.example.content.manager.ShareMgr
import com.example.content.repository.bean.FollowReq
import com.example.content.repository.bean.ProductInfo
import com.example.content.repository.bean.UserActionReq
import com.example.content.viewmodule.login.TokenStore
import com.example.core.extensions.showToast
import com.example.uiwidegt.view.banner.RadiusImageBanner
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView
import com.xuexiang.xui.widget.banner.widget.banner.BannerItem

/**
 * Created by zhudongao
 * Desc
 * Date 5/14/21
 */
class CommonListBindListener(val fragment: Fragment) : BindListener<ProductInfo> {

    private var resourceType = 3
    private var creationType = 2
    private var selectFlowTab = 0
    var flowSelectListener: FlowSelectListener? = null
    private var currentTime: Long = 0

    override fun convert(holder: BaseViewHolder, item: ItemEntity<ProductInfo>) {
        val imags = item.data.resource_list
        val trueImages = mutableListOf<String>()
        for (img in imags) {
            trueImages.add(img.convertUrl())
        }
        when (holder.itemViewType) {
            HOME_BANNER -> {
                val banner = holder.getView<RadiusImageBanner>(R.id.banner)
                val bannerData = mutableListOf<BannerItem>()

                // TODO: 2/27/21
                for (img in urls) {
                    val bannerItem = BannerItem()
                    bannerItem.imgUrl = img
                    bannerData.add(bannerItem)
                }
                banner.setSource(bannerData)
                    .setOnItemClickListener { _, _, position ->
                        App.appContext.showToast("点击了：${titles[position % titles.size]}")
                    }.startScroll()
            }
            PHOTO_LIST_TYPE -> {
                val recycler = holder.getView<RecyclerView>(R.id.recycler_view)
                val photoListAdapter = HomeRecyclerAdapter()
                val dataList = mutableListOf<IVItemEntity>()
                for (i in trueImages) {
                    val element = IVItemEntity(GRID_TYPE, i)
                    element.productId = item.data.id
                    dataList.add(element)
                }
                recycler.setItemViewCacheSize(7)
                photoListAdapter.resourceList.addAll(trueImages)
                photoListAdapter.data = dataList
                recycler.adapter = photoListAdapter
                val layoutManager = GridLayoutManager(recycler.context, 3)
                recycler.layoutManager = layoutManager
                if (recycler.itemDecorationCount < 2) {
                    recycler.addItemDecoration(
                        DividerItemDecoration(
                            recycler.context,
                            DividerItemDecoration.HORIZONTAL
                        )
                    )
                    recycler.addItemDecoration(
                        DividerItemDecoration(
                            recycler.context,
                            DividerItemDecoration.VERTICAL
                        )
                    )
                }
                clickListener(holder, item as HomeItemEntity)
            }
            VIDEO_TYPE -> {
                var url = ""
                if (item.data.resource_list.isNotEmpty()) {
                    url = item.data.resource_list[0].convertUrl()
                }
                val player = holder.getView<StandardGSYVideoPlayer>(R.id.video_show)
                val thumbImageView = ImageView(player.context)
                Glide.with(player.context).load(item.data.cover?.convertUrl())
                    .into(thumbImageView)
                player.backButton.visibility = View.GONE
                val options = GSYVideoOptionBuilder()
                options.setIsTouchWiget(true)
                    .setNeedShowWifiTip(true)
                    .setRotateViewAuto(false)
                    .setLockLand(false)
                    .setAutoFullWithSize(false)
                    .setShowFullAnimation(false)
                    .setNeedLockFull(true)
                    .setUrl(url)
                    .setThumbImageView(thumbImageView)
                    .setCacheWithPlay(true)
                    .setGSYStateUiListener {
                        if (it == GSYVideoView.CURRENT_STATE_AUTO_COMPLETE) {
                            player.startButton.visibility = View.GONE
                            val newThumbView = LayoutInflater.from(player.context)
                                .inflate(R.layout.item_video_replay_layout, null)
                            val replayView = newThumbView.findViewById<View>(R.id.replay)
                            replayView.setOnClickListener {
                                player.startPlayLogic()
                            }
                            player.thumbImageView = newThumbView
                        }
                    }
                    .build(player)
                player.fullscreenButton.setOnClickListener {
                    player.startWindowFullscreen(
                        player.context,
                        true,
                        true
                    )
                }
                clickListener(holder, item as HomeItemEntity)
            }
            FLOW_ITEM_TYPE -> {
                val recycler = holder.getView<RecyclerView>(R.id.recycler_view)
                val flowAdapter = RecyclerAdapter(object :
                    BindListener<Pair<String, Boolean>> {
                    override fun convert(
                        holder: BaseViewHolder,
                        item: ItemEntity<Pair<String, Boolean>>
                    ) {
                        val text = holder.getView<TextView>(R.id.text)
                        text.text = item.data.first
                        val isSelected = item.data.second
                        if (isSelected) {
                            holder.itemView.isSelected = true
                            text.textSize = 15f
                        } else {
                            holder.itemView.isSelected = false
                            text.textSize = 11f
                        }
                    }
                })
                for (i in FLOW_ARRAY.indices) {
                    val pair = if (i == selectFlowTab) {
                        Pair(FLOW_ARRAY[i], true)
                    } else {
                        Pair(FLOW_ARRAY[i], false)
                    }
                    flowAdapter.addData(ItemEntity(data = pair))
                }
                flowAdapter.addItemView(R.layout.oval_flow_item)
                recycler.adapter = flowAdapter
                val manager =
                    LinearLayoutManager(recycler.context, RecyclerView.HORIZONTAL, false)
                recycler.layoutManager = manager
                flowAdapter.setOnItemClickListener { adapter, view, position ->
                    val datas = flowAdapter.data
                    for (poi in datas.indices) {
                        val flowData = datas[poi].data
                        if (poi == position) {
                            datas[poi].data = Pair(flowData.first, true)
                        } else {
                            datas[poi].data = Pair(flowData.first, false)
                        }
                        resourceType = when (flowData.first) {
                            "图片" -> {
                                2
                            }
                            "视频" -> {
                                1
                            }
                            else -> {
                                3
                            }
                        }
                        creationType = if ("热门" == flowData.first) {
                            1
                        } else {
                            2
                        }
                        flowSelectListener?.onSelect(resourceType, creationType)
                    }
                    selectFlowTab = position
                    flowAdapter.notifyDataSetChanged()
                }
            }
        }
    }

    private fun clickListener(holder: BaseViewHolder, item: HomeItemEntity) {
        val headIcon = holder.getView<ImageView>(R.id.head_icon)
        val context = fragment.context
        if (context != null) {
            Glide.with(context).load(item.userInfo.avatar).into(headIcon)
        }
        headIcon.setOnClickListener {
            val bundle = Bundle()
            bundle.putInt(USER_ID, item.userId)
            bundle.putInt(KEY_FRAGMENT, PERSONAL_INFO_CENTER)
            ActivityMgr.startFragment(bundle)
        }
        val nickName = holder.getView<TextView>(R.id.nick_name)
        nickName.text = item.userInfo.nickname

        val signature = holder.getView<TextView>(R.id.user_identify)
        signature.text = item.userInfo.signature

        val desc = holder.getView<TextView>(R.id.description)
        desc.text = item.description

        val read = holder.getView<View>(R.id.read_count_container)
        val readNum = holder.getView<TextView>(R.id.view_num)
        readNum.text = item.viewNum.toString()

        //定位
        val location = holder.getView<TextView>(R.id.location_name)
        location.text = item.recommendItem.location
        //打赏
//        val reward = holder.getView<View>(R.id.reward)
//        val rewardNum = holder.getView<TextView>(R.id.reward_num)
//        val rewardImg = holder.getView<ImageView>(R.id.reward_img)
//        if (item.recommendItem.reward_related) {
//            rewardImg.setImageResource(R.drawable.ic_rewarded)
//        }
//        rewardNum.text = item.rewardNum.toString()
//        reward.setOnClickListener {
//            val pop = RewardCoinPop(reward.context)
//            pop.showPopupWindow()
//        }
        //关注
        val follow = holder.getView<TextView>(R.id.follow)
        if (item.userInfo.id == TokenStore.userId) {
            follow.visibility = View.GONE
        } else {
            follow.visibility = View.VISIBLE
        }
        if (item.isFollow) {
            follow.text = context?.getString(R.string.already_follow)
            follow.setTextColor(Color.parseColor("#999999"))
        } else {
            follow.text = context?.getString(R.string.follow)
            follow.setTextColor(Color.parseColor("#FF4C6A"))
        }
        follow.setOnClickListener {
            val req = FollowReq(item.userId, if (item.isFollow) UN_ACTION else DO_ACTION)
            item.funAction?.follow(req)
            if (item.isFollow) {
                follow.text = context?.getString(R.string.already_follow)
                follow.setTextColor(Color.parseColor("#999999"))
            } else {
                follow.text = context?.getString(R.string.follow)
                follow.setTextColor(Color.parseColor("#FF4C6A"))
            }
        }
        //收藏点赞
        val collection = holder.getView<View>(R.id.collection)
        val collectImg = holder.getView<ImageView>(R.id.collect_img)
        val collectNum = holder.getView<TextView>(R.id.collect_num)
        // TODO: 6/4/21
        if (item.recommendItem.like_related) {
            collectImg.setImageResource(R.drawable.ic_collected)
        } else {
            collectImg.setImageResource(R.drawable.ic_collection_normal)
        }
        collectNum.text = item.likeNumber.toString()
        collection.setOnClickListener {
            // TODO: 6/4/21
            val userActionReq = UserActionReq(
                item.recommendItem.id,
                THUMB_UP,
                if (item.isLike) UN_ACTION else DO_ACTION
            )
            item.funAction?.userAction(userActionReq)
        }

        GlobalMgr.collect.observe(fragment, {
            if (item.recommendItem.id == it.first && currentTime != it.third) {
                Log.e("testidddd", "喜欢id：" + it.first + "; " + it.second + "; " + it.third + "; currentTime: " + currentTime)
                item.isLike = it.second
                collectNum.text = item.likeNumber.toString()
                if (item.isLike) {
                    collectImg.setImageResource(R.drawable.ic_collected)
                } else {
                    collectImg.setImageResource(R.drawable.ic_collection_normal)
                }
                currentTime = it.third
            }
        })

        GlobalMgr.userInfo.observe(fragment, {
            fragment.context?.let { it1 -> Glide.with(it1).load(it.avatar.convertUrl()).into(headIcon) }
            nickName.text = it.nickname
            signature.text = it.signature
            item.userInfo.nickname = it.nickname
            item.userInfo.signature = it.signature
            item.userInfo.avatar = it.avatar
        })

        GlobalMgr.follow.observe(fragment, {
            if (it.follow == item.userId) {
                if (it.follow_related == FOLLOW_UN) {
                    follow.text = context?.getString(R.string.follow)
                    follow.setTextColor(Color.parseColor("#FF4C6A"))
                } else {
                    follow.text = context?.getString(R.string.already_follow)
                    follow.setTextColor(Color.parseColor("#999999"))
                }
                item.isFollow = !item.isFollow
            }
        })

        val shareMenu = holder.getView<View>(R.id.share)
        val shareNum = holder.getView<TextView>(R.id.share_num)
        shareNum.text = item.shareNum.toString()
        shareMenu.setOnClickListener {
            ShareMgr.openBottom()
        }
    }
}